﻿using flyfire.IO.Ports;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gateway.Kernel.Implements.Communication
{
    /// <summary>
    /// 串口帮助类
    /// </summary>
    public class SerialPortTransmi 
    {
        #region 事件和字段属性定义

        public event Action<byte[]> Received;

        protected CustomSerialPort SerialPort;

        #endregion 事件和字段属性定义

        /// <summary>
        /// 构造函数
        /// </summary>
        public SerialPortTransmi() : this("COM1", 9600, Parity.None, 8, StopBits.One)
        {
        }


         
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="portName">端口</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="parity">校验位</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        public SerialPortTransmi(string portName, int baudRate = 115200, Parity parity = Parity.None, int databits = 8, StopBits stopBits = StopBits.One)
        {
            try
            {
                //串口配置
                SerialPort = new CustomSerialPort(portName, baudRate, parity, databits, stopBits);
            }
            catch (Exception)
            {
                // ignored
            }
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        public bool Open()
        {
            if (!SerialPort.IsOpen)
            {
                try
                {
                    SerialPort.Open();
                    SerialPort.ReceivedEvent += SerialPort_ReceivedEvent;
                    return true;
                }
                catch (Exception)
                {
                    // ignored
                }
            }
            return false;
        }

        private void SerialPort_ReceivedEvent(object sender, byte[] bytes)
        {
            Received?.Invoke(bytes);
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public bool Close()
        {
            if (SerialPort.IsOpen)
            {
                SerialPort.ReceivedEvent -= SerialPort_ReceivedEvent;
                SerialPort.Close();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 串口是否打开
        /// </summary>
        /// <returns></returns>
        public bool IsOpen()
        {
            return SerialPort.IsOpen;
        }

        public bool Send(byte[] buffer)
        {
            if (SerialPort.IsOpen)
            {
                SerialPort.Write(buffer);
                return true;
            }

            return false;
        }

        public void Dispose() => Close();
    }
}